/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import protocol.ThreadWriter;

/**
 *
 * @author radu
 */
public class VoteListener extends Thread {

    private List<VoteInterface> voteQueue = new LinkedList<>();
    private PollList polls;

    public VoteListener(PollList _polls) {
        this.polls = _polls;
    }

    @Override
    public void run() {
        while (true) {
            VoteInterface vote;
            synchronized (voteQueue) {
                while (voteQueue.isEmpty()) {
                    try {
                        voteQueue.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ThreadWriter.class.getName()).log(Level.INFO, null, ex);
                    }
                }

                vote = voteQueue.remove(0);


                StringBuilder errorMsg = new StringBuilder();
                if (!polls.addVote(vote, errorMsg)) {
                    System.err.println("Invalid vode received " + vote + " : " + errorMsg);
                }
            }
        }
    }

    public void queueVote(VoteInterface vote) {
        synchronized (voteQueue) {
            voteQueue.add(vote);
            voteQueue.notify();
        }
    }
}